package com.mall.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.mall.entity.User;
import com.mall.enums.CodeNumEntity;
import com.mall.pojo.ResponseMessage;
import com.mall.service.UserService;
import com.mall.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: liang
 * @time: 2024-01-17 11:09
 */
@RestController
@CrossOrigin
public class UserController {

    private UserService userService;
    //Using constructor injection:
    @Autowired
    public UserController(UserService userService, Environment env) {
        this.userService = userService;
        this.env = env;
    }


    @PostMapping("/register")
    public ResponseMessage register(@RequestBody User user,@RequestParam String code) {
        if (user == null) {
            return ResponseUtil.fail();
        }
        Object dbCode = RedisUtil.get(user.getPhone());
        if (ObjectUtils.isEmpty(dbCode) || ObjectUtils.isEmpty(code) || !code.equals(dbCode)){
            return ResponseMessage.custom("-1","验证码错误...");
        }

        User newUser = userService.register(user);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", newUser);
        return ResponseUtil.successWithData(map);
    }

    @PostMapping("/resetPass")
    public ResponseMessage resetPass(@RequestParam String code,
                                     @RequestParam String phone,
                                     @RequestParam String password) {
        Object dbCode = RedisUtil.get(phone);
        if (ObjectUtils.isEmpty(dbCode) || ObjectUtils.isEmpty(code) || !code.equals(dbCode)) {
            return ResponseMessage.custom("-1", "验证码错误...");
        }

        boolean f = userService.resetPass(new User(phone, password));
        return f ? ResponseMessage.success() : ResponseMessage.custom("-1", "修改密码失败...");
    }

    //登录，返回用户信息和生成的token
    @PostMapping("/login")
    public ResponseMessage login(@RequestBody User user) {
        if (user == null) {
            return ResponseUtil.fail();
        }
        if (user.getPhone() == null || user.getPassword() == null) {
            return ResponseUtil.fail("数据传入错误");
        }
        Map<String, Object> content = userService.login(user.getPhone(), user.getPassword());
        return ResponseUtil.successWithData(content);
    }

    private final Environment env;

    //验证码登录
    @PostMapping("/sms/login")
    public ResponseMessage loginBySmsCode(@RequestParam String phone,@RequestParam String code) {
        Object dbCode = RedisUtil.get(phone);
        if (ObjectUtils.isEmpty(dbCode) || ObjectUtils.isEmpty(code) || !code.equals(dbCode)){
            return ResponseMessage.custom("-1","验证码错误...");
        }

        User dbUser = userService.queryUserByPhone(phone);
        if (ObjectUtils.isEmpty(dbUser)){
            return ResponseMessage.custom("-1","用户不存在...");
        }
        RedisUtil.del(phone);
        //生成token
        String token = TokenUtils.createToken(dbUser.getUserId(), env.getProperty("jwt.sign.property"));

        Map<String, Object> map = new HashMap<>();
        map.put("user",dbUser);
        map.put("token", token);
        return ResponseUtil.successWithData(map);
    }

    //上传\genggai用户头像,不能用于注册时上传，因为没有userId，需要首次上传使用upload
    @PostMapping("/user/avatar/{userId}")
    public ResponseMessage uploadAvatar(@PathVariable String  userId, MultipartFile file) {
        if (file == null) {
            return ResponseUtil.fail();
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = StringUtil.getUUIDRandomString(10) + suffix;
        String url;
        try {
            url = UploadFileUtil.uplaodFile(file.getInputStream(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtil.fail("文件错误");
        }

        User user = userService.uploadAvatar(url, userId);
        Map<String, Object> content = new HashMap<>();
        content.put("user", user);
        return ResponseUtil.successWithData(content);
    }


    //上传用户头像
    @PutMapping("/user")
    public ResponseMessage updateUserInfo(@RequestBody User user) {
        if (user == null || user.getUserId() == null) {
            return ResponseUtil.fail("数据传入有问题");
        }

        User newUser = userService.modifyUserInfo(user);
        Map<String, Object> content = new HashMap<>();
        content.put("user", newUser);
        return ResponseUtil.successWithData(content);
    }

    //获取用户信息
    @GetMapping("/user")
    public ResponseMessage queryUserInfo(HttpServletRequest request) {


        Map<String, Object> content = new HashMap<>();
        User user = userService.queryUserByUserId((String) request.getAttribute("userId"));
        content.put("user", user);
        return ResponseUtil.successWithData(content);
    }

    //是否登录
    @GetMapping("/isLogin")
    public ResponseMessage login(HttpServletRequest request){
        return ResponseMessage.success(UserUtils.userId(request));
    }

    //上传默认头像
    @PostMapping("/upload/default")
    public ResponseMessage uploadDefaultAvatar(MultipartFile[] files)  {
        if (files == null) {
            return ResponseUtil.fail();
        }
        List<String> urls = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        try {
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();

                String suffix = fileName.substring(fileName.lastIndexOf("."));
                fileName = StringUtil.getUUIDRandomString(10) + suffix;

                String url = UploadFileUtil.uplaodFile(file.getInputStream(), fileName);
                urls.add(url);
            }

            map.put("message", urls);


        } catch ( IOException e) {
            e.printStackTrace();
            return new ResponseMessage(CodeNumEntity.SERVER_ERROR.getCode(), CodeNumEntity.SERVER_ERROR.getMessage());

        }

        for(String url:urls)
            userService.uploadDefaultAvatar(url);
        return new ResponseMessage(CodeNumEntity.SUCCESS.getCode(), CodeNumEntity.SUCCESS.getMessage(), map);
    }

    //修改用户密码  controller
    @PutMapping("/user/password")
    public ResponseMessage modifyPassword(@RequestBody Map<String,String> data) {
        String phone=data.get("phone");
        String password=data.get("password");
        String oldPassword=data.get("oldPassword");
        if (phone == null || password == null) {
            return ResponseUtil.fail("数据传入有问题");
        }
        User user = userService.queryUserByPhone(phone);
        if (!user.getPassword().equals(oldPassword)){
            return ResponseUtil.fail("原密码不正确...");
        }
        User newUser = userService.modifyPassword(phone,password);
        //只返回code和success message
        return ResponseUtil.success();
    }

}